const co = require('co')
const {
	select,
	insert,
	insertBatch,
	update,
	executeSQL,
} = require('../db-mysql')

const table = 'tb_team'
const fields = [
	'id',
	'name',
	'introduction',
	'create_date',
	'user_id'
]

module.exports = {

	addTeam(params) {
		return co(function*() {
			let values = []
			let addFields = fields.filter((val, idx) => {
				if (val == 'id')
					return false
				if (val == 'create_date')
					values.push("NOW()")
				else
					values.push(`'${params[val] || ''}'`)
				return true
			});
			// 新团队ID results.insertId
			let results = yield insert({
				table,
				fields: addFields,
				values,
			});
			let teamId = results.insertId
			let {
				userIdList
			} = params
			userIdList = JSON.parse(userIdList)
			return yield batchUser(userIdList, teamId)
		})
	},

	updateTeam(params) {
		let {
			teamId,
			modify,
			userIdList,
			name,
			introduction,
		} = params
		userIdList = JSON.parse(userIdList)
		return co(function*() {
			yield update({
				table,
				updates: [`name = '${name}'`, `introduction = '${introduction}'`],
				where: [`id = '${teamId}'`],
			})
			if (!modify)
				return
			let SQL = `DELETE FROM tb_team_and_user WHERE team_id = '${teamId}'`
			let results = yield executeSQL(SQL)
			return batchUser(userIdList, teamId)
		})
	},

	queryTeam() {
		return select({
			table,
			fields,
		})
	},

	listTeam(userId, userRole) {
		let SQL = 'SELECT tt.id, tt.name, tt.introduction, tt.create_date, tu.realname as create_user FROM tb_team tt'
		SQL += ' LEFT JOIN tb_user tu ON tu.id = tt.user_id'
		if (userRole != 0 && userRole != 1) {
			SQL += ' LEFT JOIN tb_team_and_user ttu ON tt.id = ttu.team_id'
			SQL += ` WHERE ttu.user_id = '${userId}'`
		}
		SQL += ' ORDER BY tt.id desc;'
		return executeSQL(SQL)
	},

	teamUserList(teamId) {
		let SQL = 'SELECT tu.id, tu.nickname, tu.email, tu.realname FROM tb_user tu'
		SQL += ' LEFT JOIN tb_team_and_user ttu ON tu.id = ttu.user_id'
		SQL += ` WHERE ttu.team_id = '${teamId}'`
		return executeSQL(SQL)
	},

	teamOtherUser(teamId, userId) {
		let SQL = ''
		if (!teamId) {
			SQL = 'SELECT tu.id, tu.nickname, tu.email, tu.realname FROM tb_user tu'
			SQL += ` WHERE tu.id != '${userId}' AND tu.user_role = 2`
		} else {
			SQL = 'SELECT tu.id, tu.nickname, tu.email, tu.realname FROM tb_user tu'
			SQL += ` LEFT JOIN tb_team_and_user ttu ON tu.id = ttu.user_id AND ttu.team_id = ${teamId}`
			SQL += ` WHERE ttu.user_id is null AND tu.user_role = 2`
		}
		return executeSQL(SQL)
	},
}

function batchUser(userIdList, teamId) {
	let batch = []
	for (let i = 0; i < userIdList.length; i++) {
		let userId = userIdList[i]
		batch.push(`('${userId}', '${teamId}')`)
	}
	return insertBatch({
		table: 'tb_team_and_user',
		fields: ['user_id', 'team_id'],
		batch,
	});
}